package com.bdk.middle.cms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bdk.middle.cms.api.domain.ChannelDO;
import com.bdk.middle.cms.api.query.ChannelQueryDO;
import com.bdk.middle.cms.core.entity.ChannelEntity;
import com.bdk.middle.cms.core.entity.ChannelEntity;
import com.bdk.middle.cms.core.mapper.ChannelMapper;
import com.bdk.middle.cms.core.mapper.ChannelMapper;
import com.bdk.middle.cms.service.ChannelService;
import com.bdk.middle.common.domain.PageDO;
import com.bdk.middle.common.result.ResultDO;
import com.bdk.middle.common.status.ErrorCode;
import com.bdk.middle.common.util.BeanUtilsExtends;
import com.bdk.middle.common.util.Constant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author Reagan
 * @since 2021-03-19
 */
@Service
public class ChannelServiceImpl extends ServiceImpl<ChannelMapper, ChannelEntity> implements ChannelService {

    private Logger logger = LoggerFactory.getLogger(this.getClass().getName());

    @Autowired
    private ChannelMapper ChannelMapper;

    @Override
    public ResultDO add(ChannelDO domain) {

        ChannelEntity entity = new ChannelEntity();
        ResultDO result = BeanUtilsExtends.copy(entity, domain);
        if (!result.isSuccess()) {
            logger.debug("error code：" + result.getErrorCode().getCode() + " msg" + result.getErrorCode().getMsg());
            return result;
        }


        result = getMaxCode(domain.getChannelId(), result);//同级数量

        if (!result.isSuccess()) {
            logger.debug("error code：" + result.getErrorCode().getCode() + " msg" + result.getErrorCode().getMsg());
            return result;
        }
        int childCode = (int) result.getModel(ResultDO.FIRST_MODEL_KEY) + 1;

        if (childCode > 99) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.CATEGORY_MAX_100);
            logger.debug("error code：" + ErrorCode.CATEGORY_MAX_100.getCode() + " msg" + ErrorCode.CATEGORY_MAX_100.getMsg());
            return result;
        }

        //不够位数的在前面补0，保留两位数字
        String code = String.format("%02d", childCode);

        //查询父类目的code  如果父类目存在，子类目的code需将父类目的code添加在前
        result = getEntity(domain.getChannelId(), result);
        ChannelEntity parent = (ChannelEntity) result.getModel(ResultDO.SECOND_MODEL_KEY);
        if (parent != null) {
            code = parent.getCode() + code;
        }

        entity.setCode(code);

        int res = -1;
        try {
            res = ChannelMapper.insert(entity);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }

        //判断r的值是否小于0.如果小于0 就代表添加失败
        if (res < 0) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.CHANNEL_ADD_ERROR);
            logger.debug("error code：" + ErrorCode.CHANNEL_ADD_ERROR.getCode() + " msg" + ErrorCode.CHANNEL_ADD_ERROR.getMsg());
            return result;
        }

        return result;
    }


    @Override
    public ResultDO edit(ChannelDO domain) {

        ChannelEntity entity = new ChannelEntity();

        ResultDO result = BeanUtilsExtends.copy(entity, domain);
        if (!result.isSuccess()) {
            logger.debug("error code：" + result.getErrorCode().getCode() + " msg" + result.getErrorCode().getMsg());
            return result;
        }

        result = getEntity(domain.getId(), result);
        ChannelEntity detail = (ChannelEntity) result.getModel(ResultDO.SECOND_MODEL_KEY);

        if (!result.isSuccess()) {
            logger.debug("error code：" + result.getErrorCode().getCode() + " msg" + result.getErrorCode().getMsg());
            return result;
        }

        //当父级id更改了之后  code值也要跟着相应的更改
        if (domain.getChannelId() != null && !detail.getChannelId().equals(domain.getChannelId())) {

            result = getMaxCode(domain.getChannelId(), result);//同级数量

            if (!result.isSuccess()) {
                logger.debug("error code：" + result.getErrorCode().getCode() + " msg" + result.getErrorCode().getMsg());
                return result;
            }
            int childCode = (int) result.getModel(ResultDO.FIRST_MODEL_KEY) + 1;

            if (childCode > 99) {
                logger.debug("error code：" + ErrorCode.CHANNEL_MAX_100.getCode() + " msg" + ErrorCode.CHANNEL_MAX_100.getMsg());
                return result;
            }

            //不够位数的在前面补0，保留两位数字
            String code = String.format("%02d", childCode);

            //查询父类目的code  子类目的code需将父类目的code添加在前
            result = getEntity(domain.getChannelId(), result);
            ChannelEntity parent = (ChannelEntity) result.getModel(ResultDO.SECOND_MODEL_KEY);
            if (parent != null) {
                code = parent.getCode() + code;
            }
            entity.setCode(code);
        }

        int res = -1;
        try {
            res = ChannelMapper.updateById(entity);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }

        //判断r的值是否小于0.如果小于0 就代表添加失败
        if (res < 0) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.CHANNEL_EDIT_ERROR);
            logger.debug("error code：" + ErrorCode.CHANNEL_EDIT_ERROR.getCode() + " msg" + ErrorCode.CHANNEL_EDIT_ERROR.getMsg());
            return result;
        }

        return result;
    }

    @Override
    public ResultDO get(String id) {
        ResultDO result = new ResultDO();

        ChannelEntity entity = null;

        try {
            entity = ChannelMapper.selectById(id);
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }

        ChannelDO domain = getDomain(entity);

        result.setModel(ResultDO.FIRST_MODEL_KEY, domain);

        return result;
    }

    @Override
    public ResultDO remove(String id, String modifier) {


        ResultDO result = getEntity(id, new ResultDO());

        ChannelEntity entity = (ChannelEntity) result.getModel(ResultDO.SECOND_MODEL_KEY);

        //被删除的子类目都要被删除
        QueryWrapper<ChannelEntity> wrapper = new QueryWrapper<>();
        wrapper.likeRight("code", entity.getCode());

        int res = -1;
        try {
            res = ChannelMapper.delete(wrapper);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }

        //判断r的值是否小于0.如果小于0 就代表添加失败
        if (res < 0) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.CHANNEL_DELETE_ERROR);
            logger.debug("error code：" + ErrorCode.CHANNEL_DELETE_ERROR.getCode() + " msg" + ErrorCode.CHANNEL_DELETE_ERROR.getMsg());
            return result;
        }

        return result;
    }

    @Override
    public ResultDO find(ChannelQueryDO query) {

        ChannelEntity entity = new ChannelEntity();

        ResultDO result = BeanUtilsExtends.copy(entity, query);
        if (!result.isSuccess()) {
            logger.debug("error code：" + result.getErrorCode().getCode() + " msg" + result.getErrorCode().getMsg());
            return result;
        }
        QueryWrapper<ChannelEntity> wrapper = new QueryWrapper<>(entity);

//        wrapper.eq("is_delete", Constant.IS_DELETE_FALSE);
        Page<ChannelEntity> page = new Page<>(query.getCurrentPage(), query.getPageSize());
        IPage<ChannelEntity> iPage = null;
        try {
            iPage = ChannelMapper.selectPage(page, wrapper);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }

        List<ChannelDO> doList = getDomainList(iPage.getRecords());

        PageDO<ChannelDO> pageDO = new PageDO<>();

        pageDO.setCurrentPage(iPage.getCurrent());
        pageDO.setPageCount(iPage.getPages());
        pageDO.setPageSize(iPage.getSize());
        pageDO.setRowCount(iPage.getTotal());
        pageDO.setData(doList);

        result.setModel(ResultDO.FIRST_MODEL_KEY, pageDO);
        return result;
    }

    private ChannelDO getDomain(ChannelEntity entity) {
        ResultDO result = new ResultDO();
        //判断房源对象是否为空，为空就返回 空，不为空就进行下面的代码
        if (entity == null) return null;
        ChannelDO domain = new ChannelDO();

        if (!result.isSuccess()) {
            return null;
        }
        domain = BeanUtilsExtends.copyProperties(domain, entity) ? domain : null;

        //判断拷贝数据到Dto对象是否成功，如果成功则返回domian，如果不成功就返回空
        return domain;
    }


    private List<ChannelDO> getDomainList(List<ChannelEntity> list) {
        //创建一个名为dolist的房源do类型的 list集合
        List<ChannelDO> doList = new ArrayList<>();

        //判断传入的list的集合的size是否大于0
        if (list.size() > 0) {
            //大于0是，遍历list，创建do类型的对象 调用getdomain方法
            for (ChannelEntity entity : list) {

                ChannelDO domain = this.getDomain(entity);

                //判断得到的domain 是否为空 不为空 就往dolist集合里面添加domian 为空就返回空
                if (domain == null) {
                    return null;
                }
                doList.add(domain);
            }
        } else {
            return null;
        }
        return doList;
    }


    /**
     * 根据id查询出实体类
     *
     * @param id
     * @return
     */
    public ResultDO getEntity(String id, ResultDO result) {


        ChannelEntity entity = null;

        try {
            entity = ChannelMapper.selectById(id);
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }
        result.setModel(ResultDO.SECOND_MODEL_KEY, entity);
        return result;
    }

    /**
     * 查询同级类目的code最大值
     *
     * @param channelId
     * @return
     */
    private ResultDO getMaxCode(String channelId, ResultDO result) {

        if (result == null) {
            return null;
        }

        List<ChannelEntity> list;

        try {
            list = ChannelMapper.selectList(Wrappers.<ChannelEntity>lambdaQuery().eq(ChannelEntity::getChannelId, channelId).groupBy(ChannelEntity::getCode).orderByDesc(ChannelEntity::getCode));
        } catch (Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }

        result.setModel(ResultDO.FIRST_MODEL_KEY, list.size() > 0 && list != null ? Integer.parseInt(list.get(0).getCode().substring(list.get(0).getCode().length()-2)) : -1);
        return result;
    }

}